// pages/user/addpassenger.js
const app = getApp();

let req = require('../../utils/request.js');
let api = require('../../utils/api.js');
let phone_reg = require('../../utils/area.js').phone_reg;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    sex:['男', '女'],
    disabled: 'disabled',
    index: 0,
    info: {
      person_birth: '1970-01-01',
      paper_id: 0,
      person_gender: 0,
      person_country: '中国大陆',
      phone_reg: '+86',
      name: '',
      last_name: '',
      first_name: '',
      idcard: '',
      phone: '',
      flag: 0,
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    var id = options.id,
        _this = this,
        array = [],
        bro = [],
        reg = [],
        info

    //格式化国家及地区
    for (var i in phone_reg) {
      var arr = i.split('-')
      array.push(arr[1])
      bro.push(arr[2])
      reg.push(phone_reg[i])
    }

    if(id != 0 || id == undefined) {
      req.request(
        api.getUserPassengerInfo,
        {method: 'POST', data: {id: id}},
        function(res) {
          res = res.data
          var index = 0,
            flag = 1,
            country = res.person_country
          info = res
          for (var i in array) {
            if (array[i] == country) {
              index = i
            }
          }
          _this.setData({ info: res, index: index, 'info.phone_reg': '+' + bro[index] ,flag: flag})
        }
      )
    }

    req.request(
      api.getPaperTypes,
      { method: '', data: '' },
      function (res) {
        wx.hideLoading()
        res = res.data
        _this.setData({ range: res, array: array, id: id, bro: bro, reg: reg })
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  selectPapers(e) {
    var index = e.detail.value
    this.setData({ 'info.paper_id': index });
  },
  bindSexChange: function (e) {
    this.setData({ 'info.person_gender': e.detail.value });
  },
  bindPickerChange: function (e) {
    var index = e.detail.value,
        range = this.data.array,
        bro = this.data.bro
    this.setData({
      'info.person_country': range[index],
      'info.phone_reg': '+'+ bro[index],
       index: index 
    })
  },
  selectBirth: function (e) {
    this.setData({
      'info.person_birth': e.detail.value
    })
  },
  Pname: function(e){
    var _this = this,
      name = e.detail.value
    _this.setData({'info.name': name})
    _this.checkLegal(_this)
  },
  Judgment: function (e) {
    var _this = this,
      phone = e.detail.value,
      index = _this.data.index,
      reg = _this.data.reg[index],
      flag = _this.data.flag,
      data = {}
    if (!(reg.test(phone))) {
      wx.showToast({
        title: '手机号输入不正确',
        icon: 'none'
      })
      flag = 0
    }
    else {
      flag = 1
    }
    _this.setData({ 'info.phone': phone, flag: flag })
    _this.checkLegal(_this)
  },
  Plastname: function(e){
    var _this = this,
      last_name = e.detail.value
    _this.setData({ 'info.last_name': last_name})
    _this.checkLegal(_this)
  },
  Pfirstname: function (e) {
    var _this = this,
      first_name = e.detail.value
    _this.setData({'info.first_name': first_name})
    _this.checkLegal(_this)
  },
  Pcard: function (e) {
    var _this = this,
      idcard = e.detail.value
    _this.setData({'info.idcard': idcard})
    _this.checkLegal(_this)
  },
  
  checkLegal(_this) {
    var _this = this,
      name = _this.data.info.name,
      last_name = _this.data.info.last_name,
      first_name = _this.data.info.first_name,
      idcard = _this.data.info.idcard,
      phone = _this.data.info.phone,
      flag = _this.data.flag,
      data = {}
    
    if (name != '' && last_name != '' && phone != '' && first_name != '' && idcard !=''  && flag == 1) data['disabled'] = ''
    else data['disabled'] = 'disabled'
    _this.setData(data);
  },
  submit(e) {
    var value = e.detail.value,
        _this = this,
        id = _this.data.id,
        token = app.globalData.userInfo.user_token

    value['user_token'] = token
    value['person_id'] = id
    wx.showLoading({
      title: '加载中'
    })

    req.request(
      api.editUserPassengerInfo,
      {method: 'POST', data: value},
      function(res) {
        var result = res.data
        
        wx.hideLoading();

        wx.showToast({
          title: result.msg,
          icon: 'none'
        })

        if (result.status == 1) {
          setTimeout(function() {
            wx.navigateBack({
              delta: 1
            })
          }, 2000)
        
          //TODO 更新本地缓存 wx.setStorageSnyc()
          wx.getStorage({
            key: 'custom',
            success: function(res) {
              var custom = res.data
              var data = {}

              data['paper_name'] = value['paper_name']
              data['person_paper_number'] = value['person_paper_number']
              data['person_name'] = value['person_name']
              data['person_phone'] = value['person_phone']
              data['phone_reg'] = value['phone_reg']
              if (id == 0) {   //添加
                data['person_id'] = result.person_id
                custom.push(data)
              }else {       //编辑
                data['person_id'] = value['person_id']
                var index = 0
                for(var i in custom) {
                  custom[i]['person_id'] = data['person_id']
                  index = i
                }
                console.info(i)
                var a = custom.splice(i, 1, data)
                console.info(a)
              }
              console.info(custom)
              wx.setStorageSync('custom', custom);

            },
          })
          
        }
      }
    )
  }
})